/*
  TagView store module  标签页 
*/
import { defineStore } from 'pinia';
import router from '@/router';
import { Router, RouteRecordRaw, useRouter } from 'vue-router';

interface State {
  tagRouteList: IStores.ITagviewItem[];
}

export const useTagviewStore = defineStore('tagviewStore', {
  state: (): State => ({
    tagRouteList: [],
  }),
  getters: {},
  actions: {
    changeTagviewItem(payload: IStores.ITagviewItem) {
      // tagview发生改变先全部 opened = false
      this.tagRouteList.map((tagItem: IStores.ITagviewItem) => {
        tagItem.mode === payload.mode && tagItem.opened && (tagItem.opened = false);
        return tagItem;
      });
      const index = this.tagRouteList.findIndex((item) => item.path === payload.path);
      if (index === -1) {
        this.tagRouteList.push(payload);
        router.push(payload.path);
      } else {
        this.tagRouteList[index].opened = true;
        router.push(payload.path);
      }
    },
    removeTagviewItem(e: Event, payload: IStores.ITagviewItem) {
      e.stopPropagation();

      const index = this.tagRouteList.findIndex((item) => item.path === payload.path);
      this.tagRouteList.splice(index, 1);
      // 默认选中
      if (this.tagRouteList.length !== 0) {
        this.changeTagviewItem(this.tagRouteList[index - 1] || this.tagRouteList[index]);
      } else {
        const routerList: RouteRecordRaw[] = router.options.routes.filter((res) => {
          return res.name === payload.mode;
        });
        // 如果全部删完就默认加载 当前mode下的第一个子路由
        this.changeTagviewItem({
          mode: payload.mode,
          name: routerList[0].children![0]?.name as string,
          path: routerList[0].path + '/' + routerList[0].children![0]?.path,
          opened: true,
        });
      }
    },
  },
});
